var treeObj;
var markDataTable;
var categoryIds;
var name;
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt) { // author: meizz
	var o = {
		"M+": this.getMonth() + 1, // 月份
		"d+": this.getDate(), // 日
		"H+": this.getHours(), // 小时
		"m+": this.getMinutes(), // 分
		"s+": this.getSeconds(), // 秒
		"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
		"S": this.getMilliseconds() // 毫秒
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

/*
 * String.prototype.startWith = function(str) { var reg = new RegExp("^" + str);
 * return reg.test(this); }
 * 
 * String.prototype.endWith = function(str) { var reg = new RegExp(str + "$");
 * return reg.test(this); }
 */

/**
 * 修改名称
 * 
 * @param {Object}
 *            e
 * @param {Object}
 *            treeId
 * @param {Object}
 *            treeNode
 * @param {Object}
 *            isCancel
 */
function onRename(e, treeId, treeNode, isCancel) {
	console.log('treeNode.id:' + treeNode.id);
	if(!treeObj) {
		treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	}

	var id = treeNode.id;
	var name = treeNode.name;
	var pid = treeNode.pId;

	$.ajax({
		type: "post",
		url: getRequestUrlAddress("/category/rename.json"),
		data: {
			id: id,
			title: name,
			pid: pid
		},
		success: function(data) {
			if(!data.success) {
				$.eWin.alert("修改节点失败!");
			} else {
				treeNode.id = data.item;
				treeObj.updateNode(treeNode);
			}
		},
		error: function() {
			$.eWin.alert("修改节点失败!");
		}
	});
}

function getRequestUrlAddress(url) {
	if(url.startsWith("/")) {
		return _baseurl + url;
	}
	return _baseurl + '/' + url;
}

/**
 * 在节点删除之前执行
 * 
 * @param {Object}
 *            treeId
 * @param {Object}
 *            treeNode
 */
function beforeRemove(treeId, treeNode) {

	if(!treeObj) {
		treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	}

	var id = treeNode.id;
	var name = treeNode.name;
	var msg = "是否确认删除" + name + "节点";
	$.eWin.confirm({
		message: msg
	}).on(function(e) {
		if(!e) {
			return false;
		}
		$.ajax({
			type: "post",
			url: getRequestUrlAddress("/category/remove.json"),
			data: {
				id: id
			},
			async: true,
			success: function(data) {
				if(!data.success) {
					$.eWin.alert(data.message);
					return false;
				} else {
					treeObj.removeNode(treeNode);
					return true;
				}
			},
			error: function() {
				$.eWin.alert("删除节点失败!");
				return false;
			}
		});
	});

	return false;
}

function setRemoveBtn(treeId, treeNode) {
	return !treeNode.isParent;
}

var newCount = 1;

function addHoverDom(treeId, treeNode) {
	if(!treeObj) {
		treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	}
	var sObj = $("#" + treeNode.tId + "_span");
	if(treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
	var addStr = "<span class='button add' id='addBtn_" + treeNode.tId +
		"' title='add node' onfocus='this.blur();'></span>";
	sObj.after(addStr);
	var btn = $("#addBtn_" + treeNode.tId);
	if(btn) btn.bind("click", function() {

		while(true) {
			newCount = newCount + 1;
			var node = treeObj.getNodeByParam('id', newCount, null);
			if(!node) {
				break;
			}
		}

		treeObj.addNodes(treeNode, {
			id: newCount,
			pId: treeNode.id,
			name: "new node" + newCount
		});
		return false;
	});
};

function removeHoverDom(treeId, treeNode) {
	$("#addBtn_" + treeNode.tId).unbind().remove();
};

function zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
	/**
	 * moveType == prev || next ,pid 不变，顺序变化 moveType == inner || 成为子节点，顺序变化
	 * 
	 * 
	 * if targetNode.pid != treeNodes[0].pid && moveType == prev
	 * 说明pid变化成targetNode.pid，顺序在treeNodes[0]之前 if targetNode.pid !=
	 * treeNodes[0].pid && moveType == inner 说明pid变化成targetNode.id，顺序在最后 if
	 * targetNode.pid != treeNodes[0].pid && moveType == next
	 * 说明pid变化成targetNode.pid，顺序在treeNodes[0]之后 if targetNode.pid ==
	 * treeNodes[0].pid && moveType == prev 顺序在treeNodes[0]之前 if targetNode.pid ==
	 * treeNodes[0].pid && moveType == inner 说明pid变化成targetNode.id，顺序在最后 if
	 * targetNode.pid != treeNodes[0].pid && moveType == next 顺序在treeNodes[0]之后
	 */
	var pid = targetNode.pid;

	if(moveType == 'inner') {
		pid = targetNode.id;
	}

	var ids = "";

	for(var index = 0; index < treeNodes.length; index++) {
		var treeNode = treeNodes[index];
		var id = treeNode.id;
		if(ids == "") {
			ids = id;
		} else {
			ids = ids + "," + id;
		}
	}

	$.ajax({
		type: "get",
		url: getRequestUrlAddress("category/onDrop.json"),
		data: {
			moveIds: ids,
			parentId: pid
		},
		async: false,
		success: function(data) {
			return data.success;
		},
		error: function() {
			return false;
		}
	});
};

function loadTreeNode(ztreeOnClick, onRename, beforeRemove, onRemove) {
	// 组织树参数
	var setting = {
		async: {
			enable: true,
			url: getRequestUrlAddress("category/loadCategoryTree.json"),
			autoParam: ["id"]
		},
		edit: {
			enable: true,
			showRemoveBtn: setRemoveBtn,
			showRenameBtn: true
		},
		view: {
			addHoverDom: addHoverDom,
			removeHoverDom: removeHoverDom,
		},
		data: {
			key: {
				name: "name"
			},
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pid",

			},
			view: {
				selectedMulti: true
			}
		},
		callback: {
			onClick: ztreeOnClick,
			beforeRemove: beforeRemove,
			onRemove: onRemove,
			onRename: onRename,
			beforeDrop: zTreeBeforeDrop
		}
	};

	$.get("loadCategoryTree.json", function(result) {
		if(result) {
			$.fn.zTree.init($("#treeDemo"), setting, result);
		}
	});
}

$("#searchCategory").click(function() {
	categoryIds = null;
	name = '';
	$("#markName").val('');
	var val = $("#categoryName").val();
	var highlightNodes = new Array();
	if(!treeObj) {
		treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	}
	treeObj.expandAll(false);
	treeObj.refresh();

	highlightNodes = treeObj.getNodesByParamFuzzy("name", val, null);

	if(highlightNodes) {
		for(var i in highlightNodes) {
			treeObj.selectNode(highlightNodes[i], true);
			if(!categoryIds) {
				categoryIds = highlightNodes[i].id;
			} else {
				categoryIds += "," + highlightNodes[i].id;
			}
		}
		queryMarkByCategorys();
	}
});

$("#searchBy").click(function() {
	name = $("#markName").val();
	categoryIds = '';
	queryMarkByCategorys();
});

/**
 * 查询标签
 * 
 * @param {Object}
 *            pageNumber
 * @param {Object}
 *            pageSize
 */
function queryMarkByCategorys(pageNumber, pageSize) {
	// if(!categoryIds) {
	// $('#bootstrapPaginator').bootstrapPaginator();
	// $("#markData tbody").html("<tr><td colspan='7'>未查询到结果</td></tr>");
	// return;
	// }
	if(!pageSize) {
		pageSize = $("#tpageNumber").val();
	}
	if(!pageNumber) {
		pageNumber = 0;
	} else {
		pageNumber = pageNumber - 1;
	}

	$.ajax({
		url: getRequestUrlAddress("/mark/queryMarks.json"),
		data: {
			categoryIds: categoryIds,
			name: name,
			size: pageSize,
			page: pageNumber
		},
		success: function(result) {
			if(result.item) {
				var paginator = result.item;
				if(paginator.totalPages < 1) {
					$('#bootstrapPaginator').bootstrapPaginator({
						currentPage: (paginator.number + 1),
						totalPages: 1,
						numberOfPages: 10
					});
					$("#markData tbody").html("<tr><td colspan='2'>未查询到结果</td></tr>");
					return;
				}
				$('#bootstrapPaginator').bootstrapPaginator({
					currentPage: (paginator.number + 1),
					totalPages: paginator.totalPages,
					numberOfPages: 10
				});

				var data = result.item.content;

				$("#markData tbody").empty();
				for(var index in data) {
					var name, hreflink, categoryName;
					if(data[index].name.length > 75) {
						name = data[index].name.substring(0, 75) + '...';
					} else {
						name = data[index].name;
					}
					/*
					 * if(data[index].href.length > 45) { hreflink =
					 * data[index].href.substring(0, 45) + '...'; } else {
					 * hreflink = data[index].href }
					 */
					if(data[index].categoryName.length > 25) {
						categoryName = data[index].categoryName.substring(0, 25) + '...';
					} else {
						categoryName = data[index].categoryName
					}

					// <td title='" + data[index].href + "'>" + (hreflink) +
					// "</td>
					var hrefId = 't' + data[index].hrefHashCode;
					$("#markData tbody").append(
						"<tr>" +
						"<td title='" + data[index].name + "(" + data[index].href + ")' class='td-mark'>" +
						"<a style='color:grey;' id='" + hrefId + "' href='#' >" + (name) + "</a>" +
						"<img class='loading-z' src='" + _baseurl + "/img/loading-z.gif'/>" +
						"&nbsp;&nbsp;&nbsp;<a title='查看内容' style='float:right;' onclick=\"readMarkView('" + data[index].href + "');\"><i class='glyphicon glyphicon-search'></i></a>" +
						"<a title='删除标签' class='dM' style='float:right;' mark-id='" + data[index].id + "'><i class=\"glyphicon glyphicon-remove\"></i></a>" +
						/*
						 * "<img class='dM' mark-id='" + data[index].id + "'
						 * style='float:right;' src='" + _baseurl +
						 * "/img/delete.png' />" +
						 */
						"</td>" +
						"<td title='" + data[index].categoryName + "' mark-id='" + data[index].id + "' class='td-category'>" +
						(categoryName) +
						"<a style='float:right;' title='编辑分类'><i class=\"glyphicon glyphicon-edit\"></i></a>" +
						"</td>" +
						"</tr>");
					ckeckConnection(data[index].href, hrefId);
				}

				$(".td-category a").click(function() {
					selectCategoryOption(this);
				});

				$(".td-mark .dM").click(function() {
					deleteMark(this);
				});
			}
		}
	});
}

function deleteMark(obj) {
	var id = $(obj).attr('mark-id');

	$.eWin.confirm({
		message: "确认是否删除此书签!"
	}).on(function(e) {
		if(e) {
			removeMark(id, function(data) {
				if(data.success) {
					$(obj).parents("tr").remove();
				}
			});
		}
	})

}

function selectCategoryOption(obj) {

	var td = $(obj).parent();
	var select = '<select class="js-data-example-ajax form-control">' +
		'<option value = "3620194" selected = "selected">输入/选择</option>' +
		'</select>';
	td.html(select);

	function formatRepo(repo) {
		return repo.title;
	}

	function formatRepoSelection(repo) {
		if(repo.text) {
			return repo.text;
		}

		var id = td.attr('mark-id');
		$.ajax({
			type: "get",
			url: getRequestUrlAddress("/mark/moveMarkToCategory.json"),
			data: {
				id: id,
				categoryId: repo.id
			},
			success: function(result) {
				if(result.success) {
					td.html(repo.title + "<img style='float:right;' src='" + _baseurl + "/img/edit.png'/>");
					td.children("img").bind("click", function() {
						selectCategoryOption(this);
					});
				}
			}
		});
		return "error";
	}
	$(".js-data-example-ajax").select2({
		ajax: {
			url: "findCategoryByName.json",
			dataType: 'json',
			delay: 250,
			data: function(params) {
				return {
					q: params.term, // search term
					page: params.page
				};
			},
			processResults: function(data, params) {
				// parse the results into the format expected by Select2
				// since we are using custom formatting functions we do not need
				// to
				// alter the remote JSON data, except to indicate that infinite
				// scrolling can be used
				params.page = params.page || 1;

				return {
					results: data.items,
					pagination: {
						more: (params.page * 30) < data.total_count
					}
				};
			},
			cache: true
		},
		escapeMarkup: function(markup) {
			return markup;
		}, // let our custom formatter work
		minimumInputLength: 1,
		templateResult: formatRepo, // omitted for brevity, see the source of
									// this page
		templateSelection: formatRepoSelection // omitted for brevity, see the
												// source of this page

	});
}

/**
 * 检测url打开是否正常
 * 
 * @param {Object}
 *            hrefStr 链接
 * @param {Object}
 *            hrefId 链接id
 */
function ckeckConnection1(hrefStr, hrefId) {
	if((-1 != hrefStr.indexOf("http://") || -1 != hrefStr.indexOf("https://"))) {
		$.ajax({
			type: "get",
			url: getRequestUrlAddress("category/isConnection.json?urlAddress=" + hrefStr),
			cache: false,
			success: function(data) {
				$("#" + hrefId).attr("href", hrefStr);
				$("#" + hrefId).attr("target", "_blank");
				if(data.success) {
					$("#" + hrefId).parent().find('.loading-z').remove(); // 删除div下的子元素li
					$("#" + hrefId).parent().find('.dM').remove(); // 删除div下的子元素li
					$("#" + hrefId).css('color', '#337ab7');
				} else {
					$("#" + hrefId).parent().find('.loading-z').remove(); // 删除div下的子元素li
				}
				console.log("success -- [" + hrefStr + "]:{status:" + data.success + "}");
			}
		});
	}
}
/**
 * 检测url打开是否正常
 * 
 * @param {Object}
 *            hrefStr 链接
 * @param {Object}
 *            hrefId 链接id
 */
function ckeckConnection(hrefStr, hrefId) {
	$("#" + hrefId).attr("href", hrefStr);
	$("#" + hrefId).attr("target", "_blank");
	if((-1 != hrefStr.indexOf("http://") || -1 != hrefStr.indexOf("https://"))) {
		$.ajax({
			type: "get",
			url: hrefStr,
			dataType: 'jsonp',
			jsonp: 'jc',
			timeout: 10000,
			complete: function(response, textStatus) {
				if(response.status == 200) {
					$("#" + hrefId).parent().find('.loading-z').remove(); // 删除div下的子元素li
					$("#" + hrefId).parent().find('.dM').remove(); // 删除div下的子元素li
					$("#" + hrefId).css('color', '#337ab7');
				} else {
					$("#" + hrefId).parent().find('.loading-z').remove(); // 删除div下的子元素li
				}
				console.log("complete -- [" + hrefStr + "]:{status:" + response.status + "," + textStatus + "}");
			}
		});
	}
}

var treeOnclick = function(event, treeId, treeNode) {
	categoryIds = treeNode.id;
	name = '';
	$("#markName").val('');
	queryMarkByCategorys();
}

$("#repeatViewButton").click(function() {
	$.ajax({
		type: "get",
		url: getRequestUrlAddress("category/repeatCategory"),
		async: true,
		success: function(data) {
			$("#repeatCategory").html(data);
			$("#repeatCategory").modal({
				show: true
			});
		}
	});
});

$("#relChartViewButton").click(function(){
	window.location.href = "/category/relChart.htm";
});

function readMarkView(url) {

	// window.open(getRequestUrlAddress("mark/readMark?url=" + url));

	var temp = document.createElement("form");
	temp.action = getRequestUrlAddress("blog/readMark");
	temp.method = "post";
	temp.target = "_blank";
	temp.style.display = "none";

	var opt = document.createElement("textarea");
	opt.name = "url";
	opt.value = url;
	temp.appendChild(opt);

	document.body.appendChild(temp);
	temp.submit();
	return temp;

	// $.ajax({
	// type: "get",
	// url: getRequestUrlAddress("mark/readMark?url="+url),
	// async: true,
	// success: function(data) {
	// $("#readMark").html(data);
	// $("#readMark").modal({
	// show: true
	// });
	// }
	// });
}

$("#repeatMarkViewButton").click(function() {
	$.ajax({
		type: "get",
		url: getRequestUrlAddress("/mark/repeatMark"),
		async: true,
		success: function(data) {
			$("#repeatMark").html(data);
			$("#repeatMark").modal({
				show: true
			});
		}
	});
});

$("#file-0a").fileinput({
	showPreview: false,
	language: 'zh',
	uploadUrl: getRequestUrlAddress('/mark/brower/uploadMarkFile'),
	allowedFileExtensions: ['html', 'htm'],
}).on('filebatchpreupload', function(event, data, id, index) {
	$('#kv-success-1').html('<h4>上传信息提示</h4><ul></ul>').hide();
	$('#kv-error-1').html('<h4>上传信息提示</h4><ul></ul>').hide();
}).on('fileuploaded', function(event, data, id, index) {
	var fname = data.files[index].name,
		out = '<li>' + '导入书签文件并解析 # ' + (index + 1) + ' - ' +
		fname + ' 成功.' + '</li>';
	$('#kv-success-1 ul').append(out);
	$('#kv-success-1').fadeIn('slow');

	if(!treeObj) {
		treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	}
	treeObj.reAsyncChildNodes(null, "refresh");
}).on('fileuploaderror', function(event, data, error) {
	var fname = data.files[0].name,
		out = '<li>' + error + '</li>';
	$('#kv-error-1 ul').append(out);
	$('#kv-error-1').fadeIn('slow');
});

/**
 * 合并分类
 * 
 * @param {Object}
 *            radioName
 * @param {Object}
 *            objThis
 */
function mergeC(radioName, objThis, trIdStartSuffix, trCount) {
	var mId = $('input[name="' + radioName + '"]:checked').val();
	if(mId) {
		var cIds = "";
		$('input[name="' + radioName + '"]').each(function() {
			if(!this.checked) {
				if(cIds == "") {
					cIds = this.value;
				} else {
					cIds += "," + this.value;
				}
			}
		});

		$.ajax({
			type: "get",
			url: getRequestUrlAddress("category/mergeCategory.json"),
			data: {
				'mId': mId,
				'cIds': cIds
			},
			async: true,
			success: function(data) {
				if(data.success) {
					$(objThis).attr("disabled", true);

					for(var i = 0; i < trCount; i++) {
						$("#" + trIdStartSuffix + "_" + i).remove();
					}
					$("#" + trIdStartSuffix + "_null").remove();

					if(!treeObj) {
						treeObj = $.fn.zTree.getZTreeObj("treeDemo");
					}
					treeObj.reAsyncChildNodes(null, "refresh");
				}
			}
		});
	}
}

/**
 * 删除标签
 * 
 * @param {Object}
 *            radioName
 * @param {Object}
 *            objThis
 */
function removeM(radioName, objThis, trIdStartSuffix, trCount) {
	var mId = $('input[name="' + radioName + '"]:checked').val();
	if(mId) {
		var cIds = "";
		$('input[name="' + radioName + '"]').each(function() {
			if(!this.checked) {
				if(cIds == "") {
					cIds = this.value;
				} else {
					cIds += "," + this.value;
				}
			}
		});

		removeMark(cIds, function(data) {
			if(data.success) {
				$(objThis).attr("disabled", true);
				for(var i = 0; i < trCount; i++) {
					$("#" + trIdStartSuffix + "_" + i).remove();
				}
				$("#" + trIdStartSuffix + "_null").remove();
			}
		});
	}
}

function removeMark(mIds, callback) {
	$.ajax({
		type: "get",
		url: getRequestUrlAddress("/mark/remove.json"),
		data: {
			'mIds': mIds
		},
		async: true,
		success: function(data) {
			callback(data);
		}
	});
}

$(document).ready(function() {
	loadTreeNode(treeOnclick, onRename, beforeRemove);

	$('#bootstrapPaginator').bootstrapPaginator({
		onPageClicked: function(event, originalEvent, type, page) {
			queryMarkByCategorys(page);
		}
	});

	$("#tpageNumber").select2();
});